package com.bss.dao;

import com.bss.beans.User;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.ArrayList;

public class LoginDao {
	
	public static ArrayList<String> loadUserNames() throws Exception
	{
		ResultSet Rs=null;
		String user=null;
		ArrayList<String> userlist= new ArrayList<String>();
		String selectQuerry="select username from user";
		PreparedStatement Ps;
		Connection conn=ConnectionDao.getConnection1();
		
		try{
			
			Ps=conn.prepareStatement(selectQuerry);
			Rs=Ps.executeQuery();
			
			while(Rs.next()){
			
				user=Rs.getString(1);	
				userlist.add(user);
			}
			
		}
		finally
		{
			ConnectionDao.closeConnection(conn);
		}
		
		return userlist;
		
		
	}
	
	public static boolean AddNewUser(User user) throws Exception
	{
		Connection conn;
		ResultSet Rs;
		PreparedStatement Ps;
		
		String insertString="insert into user(username,password,usertype) values(?,?,?)";
		
		conn=ConnectionDao.getConnection1();
		
		try{
			Ps=conn.prepareStatement(insertString);
			
			Ps.setString(1, user.getSUserName());
			Ps.setString(2, user.getSPassword());
			Ps.setInt(3,user.getIUserType());
			
			Ps.executeUpdate();
			
			
			
		}
		finally
		{
			ConnectionDao.closeConnection(conn);
			
		}
		
		return true;
	}
	
	public static int CheckPassword(User user) throws Exception
	{
		Connection conn;
		ResultSet Rs;
		PreparedStatement Ps;
		
		conn=ConnectionDao.getConnection1();
		
		try
		{
		
		String strSelect = "select userType,password from user where username=? ";
		
		Ps=conn.prepareStatement(strSelect);
		
		Ps.setString(1, user.getSUserName());
		
		
		Rs = Ps.executeQuery();
		while(Rs.next()){
			
			com.bss.framework.FrontController.trace("Found Record in User DataBase");
			
			if(user.getSPassword().compareTo(Rs.getString("password"))==0)
			{
			//get the USER TYPE
			int strUserType = Rs.getInt("userType");
			com.bss.framework.FrontController.trace("found USer->"+strUserType);
			ConnectionDao.closeConnection(conn);
			return strUserType;
			}
		 
					
		}
		}
		finally
		{
			ConnectionDao.closeConnection(conn);
		}
		
		return 0;
	}
	
	
	public static int ChnagePassword(String user,String newPassword) throws Exception
	{
		Connection conn;
		ResultSet Rs;
		PreparedStatement Ps;
		
		conn=ConnectionDao.getConnection1();
		
		try
		{
		
		String strSelect = "update user set password=? where username=?";
		
		Ps=conn.prepareStatement(strSelect);
		
		Ps.setString(1, newPassword);
		Ps.setString(2, user);
		
		
		Ps.executeUpdate();
		
		}
		finally
		{
			ConnectionDao.closeConnection(conn);
		}
		
		return 0;
	}

}
